import java.util.concurrent.atomic.AtomicInteger;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-10-14
 * Time:20:38
 */
public class Test01 {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        atomicInteger.getAndIncrement();//相当于i++
    }
}

// 原子类的伪代码
class AtomicInteger {
    private int value;

    public int getAndIncrement() {
        int oldValue = value;
        while (CAS(value, oldValue, oldValue + 1) != true) {
            oldValue = value;
        }
        return oldValue;
    }
}

//自旋锁伪代码
public class SpinLock {
    private Thread owner = null;
    public void lock() {
        //通过CAS看当前锁是否被某个线程占用
        //如果这个锁已经被别的线程持有，则自旋等待
        //如果这个锁没有被别的线程持有，则尝试加锁(将当前线程设为尝试加锁的线程)
        while (!CAS(this.owner, null, Thread.currentThread())) {

        }
    }
    public void unlock() {
        this.owner = null;
    }
}